﻿using System;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.IO.Compression;
using System.Text;

/// <summary>
/// Create by Kris
/// Date:20080324
///
/// </summary>
public class Zip
{
    public Zip()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 压缩数据
    /// </summary>
    /// <param name="table"></param>
    /// <returns></returns>
    public static byte[] Compress(DataTable table)
    {
        if (string.IsNullOrEmpty(table.TableName))
        {
            table.TableName = "default";
        }
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
        serializer.Serialize(writer, table);
        writer.Close();

        byte[] sourse = System.Text.Encoding.Default.GetBytes(sb.ToString());

        MemoryStream ms = new MemoryStream();
        GZipStream stream = new GZipStream(ms, CompressionMode.Compress);
        stream.Write(sourse, 0, sourse.Length);
        stream.Close();
        return ms.ToArray();

    }

    public static DataTable Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream stream = new GZipStream(input, CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buffer = new byte[4096];
        int read = -1;
        read = stream.Read(buffer, 0, buffer.Length);
        while (read > 0)
        {
            output.Write(buffer, 0, read);
            read = stream.Read(buffer, 0, buffer.Length);
        }
        stream.Close();

        string str = System.Text.Encoding.Default.GetString(output.ToArray());

        StringReader strReader = new StringReader(str);
        XmlReader xmlReader = XmlReader.Create(strReader);
        XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

        DataTable dt = (DataTable)serializer.Deserialize(xmlReader);

        return dt;
    }
}

